/**
 * Created with Vim7.3 ubuntu12.04
 * @fileOverview : share  
 * @author : Lyle <lylechen2014@gmial.com>
 * @since : 2014-08-18 11:09:34
 * @filename : static/mnm/src/share.js
 * @version : 
 * @description : 
 */

define(function(require, exports, module) {

    var share = {}, roomName = 'masonsoft';

    module.exports = share;

    share.PMSG = null;

    share.fixedBug = function() {
        $("input,select,textarea").live('focus',function() {
            $('#'+seajs.moduleUI).find('.head').css({'position':'absolute','left' : '0px'});   
        }).live('focusout',function(){
            setTimeout (function() {
                 share.blurChange();      
            },0); 
        });
    };

    share.blurChange = function() {
        var left = $('#'+seajs.moduleUI).find('.head').parent().css('left');
        $('#'+seajs.moduleUI).find('.head').css({'position':'fixed','left':left});  
    };

    share.blur = function(id) {
        var input = $('#'+id).find('input'),
            select = $('#'+id).find('select');
            textarea = $('#'+id).find('textarea');
        input.blur();
        select.blur();
        textarea.blur();
        share.blurChange();      
    };

    share.delAllPage = function() {
         $('.page').each(function(){
             var id = $(this).attr('id');
             share.delIdPage(id);
         });
    };

    share.delIdPage = function(id) {
         routerObj.delIdPage(id);
    };

    share.inputError = function(obj) {
        /** 
         obj = {
            type:
             dom:
             msg:
            bool:
         }

         */
         switch(obj.type) {
               //错误渲染方式
               case 1:

                 var dom = obj.dom;
                 if (dom.next().hasClass('err')) {
                     dom.next().remove();
                     dom.find('input').removeAttr('style').removeClass('input_err');
                 }

                 if (!obj.bool) {
                     dom.after("<div class='err'>"+obj.msg+"</div>");
                     dom.find('input').css('borderColor','#F50C70').addClass('input_err');
                 }

               break;

               case 2:
                     alert(obj.msg);
               break;

               case 3: 
                     var dom = obj.dom;
                     if (dom.next().hasClass('err')) {
                         dom.next().remove();
                     }

                     if (!obj.bool) {
                         dom.after("<div class='err'>"+obj.msg+"</div>");
                     }
               break;

         }
    };

    share.pageLoad = function(bool,dom) {
         if (bool) {
             var html = "<div id='pageLoad'></div>";
             if ($('#pageLoad').length<1) {
                 dom.append(html);
             }
         } else {
            dom.find('#pageLoad').remove();
         }

         this.pageCover(bool,dom);
    };
         
    //type console.log/alert  
    share.error = function(type,msg,obj) {
         if (type == 'console') {
             console.log(msg); 
         } else {
             alert(msg);
         }
    };

    share.pageCover = function(bool,dom) {
   	     if (bool) {
             var html = "<div id='pageLoadDiv'></div>";
             if ($('#pageLoadDiv').length < 1) {
                 html = $(html).on('touchstart touchmove touchend',function(e){
                     e.stopPropagation(); 
                     e.preventDefault(); 
                 });
                 dom.append(html);
             }
         } else {
                 dom.find('#pageLoadDiv').remove();
         }

    };

    share.ajaxStartA = function(dom) {
           dom.parent().find('.ajaxLoading').remove();
           var html = $("<div class='ajaxLoading'></div>");
	       dom.after(html);
    };

    share.ajaxEndA = function(dom) {
           dom.parent().find('.ajaxLoading').remove();
    };

    share.ajaxStartB = function(dom) {
           var html = $("<div class='listLoading'></div>");
           if (dom.find('.listLoading').length < 1) {
               dom.append(html);
           }
    };
    
    share.ajaxEndB = function(dom) {
           dom.find('.listLoading').remove();
    };
     
    share.backTopStart = function(dom,bool) {
          if ($('#backTop').length < 1) {
              var html = $("<div id='backTop'></div>");
	          dom.append(html);
              if (bool) {
                  setTimeout(function(){
                    share.backTopEnd(dom);
                  },3000);
              }
           }
    };
    
    share.handleVal = function(val) {
           if (val == undefined || val == null ) {
               val = '';
           }
           return val;
    };

    share.defaultVal = function(val) {
           if (val == undefined || val == null || val == '' ) {
               val = 'This user has not described himself/herself.';
           }
           return val;
    };

    share.backTopEnd = function() {
        $('#backTop').remove();
    };

    //ajax请求预埋管理统一接口
    share.ajaxControl = function(obj) {
        //业务逻辑
        var callback = obj.success;
        var success = function(data,status,xhr) {
            if (data.errcode == 100) {
                share.loginOut();
                window.location.href = '#signin/whole'; 
            } else if (data.errcode == 404) {
                alert(data.errmsg); 
                share.pageLoad(false,$('body'));
                share.browserClear(); 
                return;
            } else {
                callback(data,status,xhr); 
            }
        };

        obj.success = success;
        obj.timeout = 120000;
        obj.error = function(xhr, errorType, error) {
            share.pageLoad(false,$('body'));
            share.error('alert','Oops! Something\'s not right. Try again later.'); 
        }

        return obj;
    };

    share.ages = function(str) {   
        var r =  str.match(/^(\d{1,4})(-|\/)(\d{1,2})\2(\d{1,2})$/);     
        if(r==null)return false;     
        var d= new  Date(r[1],r[3]-1,r[4]);     
        if(d.getFullYear()==r[1]&&(d.getMonth()+1)==r[3]&&d.getDate()==r[4]) {   
              var Y = new Date().getFullYear();   
              return (Y-r[1]);   
        }   
        return "error";   
    };

    
    share.age = function(year) {
        var y = new Date().getFullYear();
        return y - year;
    };

    share.checkPermission = function(type,str) {
         var bool = this.accessPermission();
         if ($('#sliderDialog').length > 0){$('#sliderDialog').remove()};
         if (type) {
             if (bool) {
                 if (str) {
                     window.location.href = str; 
                 }
             } else {
                 share.delIdPage('userNav'); 
                 share.browserClear(); 
                 window.location.href = '#signin/whole';
             }
         } else {
             if (bool) {
                window.location.href = '#userList/whole';
             } 
         }
         return bool;
    }; 
    
    share.accessPermission = function() {
        var bool = false,nmmid = util.getCookie('session_id'),
            userInfo = share.getStorage("ms_user_info");

        if (nmmid && userInfo) {
            bool = true;
        }
        return bool;
    };

    share.isGuest = function() {
        var bool = false,obj = share.userInfo();
        if (obj.isGuest) {
            bool = true;
        }
        return bool;
    };
    
    share.getSessionId = function() {
        return util.getCookie('session_id');
    };

    share.editStorage = function(name,key,val) {
        var obj = JSON.parse(share.getStorage(name));
            obj[key] = val;
        share.setStorage(name,JSON.stringify(obj));
    };

    share.cacheUserList = function(obj) {
        for (var i in obj) {
            this.cacheUserInfo(obj[i].usr_id,obj[i]);
        }
    };

    share.cacheUserInfo = function(key,obj) {
        var data = JSON.parse(this.getStorage(key));
        if (data) {
            obj = _.extend(data,obj);
        }
        this.setStorage(key,JSON.stringify(obj));
    };

    share.setStorage = function(key,val) {
        sessionStorage.setItem(key,val);
    };

    share.getObjStorage = function(key) {
        return JSON.parse(sessionStorage.getItem(key));
    };

    share.getStorage = function(key) {
        return sessionStorage.getItem(key);
    };

    share.getLocalStorage = function(key) {
        var data = JSON.parse(localStorage.getItem(key));
        if (data == null || data == undefined || data == '') {
            this.setProfileOptions({ async: 0 });
            data = JSON.parse(localStorage.getItem(key));
        }
        return data;
    };


    share.userInfo = function(){
        return JSON.parse(share.getStorage("ms_user_info"));
    };

    share.loginOut = function() {
        var info = share.userInfo();
        if (info) {
            var ajaxObj = {
                url : seajs.data.vars.apiAccessUrl+'logout?usr_id='+info.usr_id,
                type : 'GET',
                success : function(data) {
                     //share.browserClear(); 
                },
                error : function(xhr, errorType, error) {
                    share.error('alert',' http request failed!'); 
                } 
            };
            $.ajax(share.ajaxControl(ajaxObj)); 
        }
        share.browserClear(); 
        /* else {
          //share.browserClear(); 
        }
        */
    };

    share.defalutImg = function(gender,img) {
            if (img == '') {
                 if (gender == 1) {
                    img = seajs.data.vars.resourceUrl+'img/icon_male.png'; 
                 } else if (gender == 2) {
                    img = seajs.data.vars.resourceUrl+'img/icon_remale.png'; 
                 } else {
                    img = seajs.data.vars.resourceUrl+'img/icon_married.png'; 
                 }
            }
            return img;
    };

    share.browserClear = function() {
        util.delCookie('session_id',{path:'/',expires:-1}); 
        sessionStorage.clear();  
        localStorage.clear();
        share.delAllPage();  
        share.delIdPage('userNav');
        window.location.href = '#index/whole';
    };

    share.getCountryList = function(obj) {
        var data = localStorage.getItem("ms_country_list");
        //console.log('236',data,obj); 
        if (data == null || data == '') {  
            var ajaxObj = {
                url : seajs.data.vars.apiUrl+'get_country_list',
                type : 'GET',
                success : function(data) {
                    if (data.results == 1 ) {
                        obj.callback(data,obj);
                        localStorage.setItem("ms_country_list",JSON.stringify(data));
                    }
                },
                error : function(xhr, errorType, error) {
                    share.error('alert',' http request failed!'); 
                } 
            };
            $.ajax(share.ajaxControl(ajaxObj)); 
        } else {
            obj.callback(JSON.parse(data),obj);
        }
    };

    share.setProfileOptions = function(opt) {
        if (typeof opt === 'undefined') {
            opt = {};
        }
        var data = localStorage.getItem("ms_height");
        if (data == null || data == '') {
            var ajaxObj = {
                url : seajs.data.vars.apiUrl+'get_profile_options',
                type : 'GET',
                async: opt.async ? true : false,
                success : function(data) {
                    if (data.results == 1 ) {
                        for (var item in data.data) {
                            localStorage.setItem("ms_" + item, JSON.stringify(data.data[item]));
                        }
                    }
                },
                error : function(xhr, errorType, error) {
                    share.error('alert',' http request failed!'); 
                } 
            };
            $.ajax(share.ajaxControl(ajaxObj)); 
        }
    };

    share.showCheckboxLabel = function(mid, val) {
        var obj = new Backbone.Collection(this.getLocalStorage(mid));
        var str = '';
        if (obj.length > 0) {
            _.each(obj.models, function(model) {
                if (parseInt(parseInt(val)&parseInt(model.get("value"))) > 0) {
                    str += model.get("label") + '</br>';
                }
            });
        }
        return str;
    };

    share.getStateList = function(obj) {
         var dataObj = localStorage.getItem("ms_state_list");
         if (dataObj == null || dataObj == undefined || dataObj == '') {
             dataObj = {};
         } else {
             dataObj = JSON.parse(dataObj);
         }
         var data = dataObj[obj.country];

         if (data == null || data == undefined || data == '') {
             var ajaxObj = {
                    url : seajs.data.vars.apiUrl + 'get_state_list?country=' + obj.country,
                    type : 'GET',
                    success : function(data) {
                        if (data.results == 1 ) {
                            obj.callback(data,obj);
                            dataObj[obj.country] = data;
                            localStorage.setItem("ms_state_list",JSON.stringify(dataObj));
                        }
                    },
                    error : function(xhr, errorType, error) {
                        share.error('alert','http request failed!'); 
                    } 
             };
             $.ajax(share.ajaxControl(ajaxObj)); 
         } else {
             obj.callback(data,obj);
         }
    };

    share.getIncomeList = function(obj) {
         var data = localStorage.getItem("ms_income_list");
         if (data == null || data == '') { 
             var ajaxObj = {
                url : seajs.data.vars.apiUrl + 'get_income_list',
                type : 'GET',
                success : function(data) {
                    if (data.results == 1 ) {
                        obj.callback(data,obj);
                    }
                },
                error : function(xhr, errorType, error) {
                    share.error('alert',' http request failed!'); 
                } 
            };
            $.ajax(share.ajaxControl(ajaxObj)); 
         } else {
            obj.callback(data,obj);
         }        
    };

    share.tabSwitch = function(dom,index) {
         dom.find('.tabInfo').find('.tabTitle').find('li').removeClass('tabTitle_selected_li');
         dom.find('.tabInfo').find('.tabContent').css('display','none');
         dom.find('.tabTitle').find('li').eq(index).addClass('tabTitle_selected_li');
         dom.find('.tabContent').eq(index).show(); 
    };

    share.updateMainPhoto = function(usr_id) {
         var userObj = JSON.parse(share.getStorage(usr_id));
         userObj.photo = (userObj.pictures[0] !== undefined && userObj.pictures.length > 0) ? userObj.pictures[0] : '';
         share.cacheUserInfo(usr_id,userObj); 
    };

    share.updateProfile = function(usr_id,callback,data) {
          //data.save = 1; 
          share.pageLoad(true,$('body'));
          var obj = {
                   //url : seajs.data.vars.apiAccessUrl+'save_profile',
                   url : seajs.data.vars.apiAccessUrl+'update_profile',
                   type : 'POST',
                   data : data,
                   success : function(data) {
                       share.pageLoad(false,$('body'));
                       //if (data.ret !== 1) {
                       if (data.errcode) { 
                          alert(data.errmsg); 
                       } else if (data.errs) {
                          alert(data.errs[0].errmsg);
                       } else {
                          callback(data);
                       }
                   }, 
                   error : function(xhr, errorType, error) {
                       share.error('alert','http request failed!'); 
                   }
          };
          $.ajax(share.ajaxControl(obj));
    };

    share.formatChatDate = function(datetime) {
            if (!datetime) {
                return;
            }
            var date_msg= new Date(share.correctChatDateString(datetime));
            var date_now= new Date();
            if (date_msg.getFullYear() == date_now.getFullYear() && date_msg.getMonth() == date_now.getMonth() && date_msg.getDate() == date_now.getDate()) {
                //return hh24:mi
                return (date_msg.getHours() + ':' + (date_msg.getMinutes() < 10 ? ('0' + date_msg.getMinutes()) : date_msg.getMinutes()));
            } else if (date_msg.getFullYear() < date_now.getFullYear()) {
                //return mm/dd/yyyy
                return ((date_msg.getMonth() + 1) + '/' + date_msg.getDate() + '/' + date_msg.getFullYear());
            } else {
                //return Mon dd, hh24:mi
                var monthArr=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];
                return (monthArr[date_msg.getMonth()] + ' ' + date_msg.getDate() + ', ' + date_msg.getHours() + ':' + (date_msg.getMinutes() < 10 ? ('0' + date_msg.getMinutes()) : date_msg.getMinutes()));
            }
    };

    share.correctChatDateString = function(datetime) {
            if (isNaN(datetime)) {
                datetime = datetime.replace(/-/g,'/');
                datetime = datetime.replace('T',' ');
                datetime = datetime.replace('Z',' ');
            }
            return datetime;
    };
 
    /**********Refactor add*********/

    share.compatibleData = function(data) {
            var userInfo = {
                   detail : {
                         basics : {
                            age_day: data.age_day,
                            age_month: data.age_month,
                            age_year: data.age_year
                         }
                   },
                   account : {
                         age :  new Date().getFullYear() - Number(data.age_year),
                         country : data.country,
                         country_name : data.country_name,
                         gender : data.gender,
                         state : data.state,
                         state_name : data.state_name,
                         username : data.username,
                         usr_id : data.usr_id
                   },
                   status : {
                         isGuest : data.isGuest,
                         income_verify : data.income_verify
                   },
                   match : {
                         match_age_max : data.match_age_max,
                         match_age_min : data.match_age_min,
                         match_gender : data.match_gender
                   },
                   photo :  typeof(data.pictures[0]) !== 'undefined' ? data.pictures[0] : null,
                   pictures : data.pictures,
                   viewed_count : data.viewed_count,
                   interested_count : data.interested_count
                }
                return userInfo; 
    };

    share.reRender = function(bool,id) {
           if (bool) {
               this.delIdPage(id);
           }
    };

    share.panel = function(panel,tpl,mId,nav,callback) {
           if ($('#userNav').length < 1) { 
               $('body').append(tpl(lang));
               panel.init();
               $('#userNav').imglazyload({startY : 0,endY: $(window).height(),sW:50,sH:50}); 
           }

           panel.run({
                navName : nav,
                rootDom : $('#'+mId),
                contentDom : $('#'+mId).find('.body_all'),
                callback: function(obj){if (callback) {callback(obj)}}
           });
    };


});
